<template>
  <div>
    <!--  面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
<!--      消息提示的文案-->
      <el-alert
        title="添加商品信息" show-icon center :closable="false"
        type="info">
      </el-alert>
<!--      步骤条-->
      <el-steps :space="200" :active="activeIndex" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRef" label-width="100px">
<!--      tabs标签页 before-leave切换标签之前的钩子  @tab-click="tabClick"-->
      <el-tabs :tab-position="'left'"  :before-leave="beforeLeave"  @tab-click="tabClick">
        <el-tab-pane label="基本信息">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="addGoodsForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price" >
            <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number" >
            <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight" >
            <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat" >
            <el-cascader
              v-model="selectCateKeys"
              :options="cateList"
              :props="props"
              @change="handleChange" clearable ></el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数">
          <!-- 渲染表单的Item项 -->
        <el-form-item v-for="(item1 ) in manyTableData" :key="item1.attr_id" :label="item1.attr_name">
<!--            这里双向绑定了 v-model="item1.attr_vals"-->
           <el-checkbox-group  v-model="item1.attr_vals">
<!--             label与数组中的元素值相对应，如果存在指定的值则为选中状态，否则为不选中。-->
            <el-checkbox border v-for="(item2 ,i) in item1.attr_vals" :key="i" :label="item2" style="margin: 15px"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-tab-pane>
        <el-tab-pane label="商品属性" >
          <el-form-item :label="item.attr_name" v-for="item in this.onlyTableData" :key="item.attr_id" label-width="150px">
<!--            这里双向绑定了 v-model="item.attr_vals"-->
            <el-input v-model="item.attr_vals"></el-input>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品图片" >
          <!--  action 图片上传url          -->
          <el-upload
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove" :on-success="uploadSuccess"
            list-type="picture" :headers="headersObj">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" >
<!--          富文本编辑器 导入依赖vue-quill-editor 然后导入main.js中全局使用-->
          <quill-editor v-model="addGoodsForm.goods_introduce">
        </quill-editor>
<!--          商品添加按钮-->
          <el-button type="primary" @click="addGood" style="margin-top: 15px">添加商品</el-button>
        </el-tab-pane>
      </el-tabs>
      </el-form>
<!--      图片预览弹框-->
      <el-dialog
        title="图片预览"
        :visible.sync="prePictureVisible"
        width="50%">
        <img :src="prePicUrl" alt="" width="100%">
        <span slot="footer" class="dialog-footer">
  </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
// import _ from 'lodash'
export default {
  data() {
    return {
      // 当前激活步骤条的index的下标值
      activeIndex: 0,
      // 商品表单
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        // 分类列表 字符串（selectCateKeys转换过来）
        goods_cat: [],
        // 上传的图片临时路径（对象）
        pics: [],
        // 商品介绍
        goods_introduce: '',
        // 商品动态参数或静态属性
        attrs: []
      },
      // 商品表单验证规则
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请输入商品分类', trigger: 'blur' }]
      },
      // 所有分类列表
      cateList: [],
      //    prop配置选项 expandTrigger次级菜单的展开方式 value指定选项的值为选项对象的某个属性值
      // label指定选项标签为选项对象的某个属性值 children指定选项的子选项为选项对象的某个属性值
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 父级id列表
      selectCateKeys: [],
      // 动态参数列表
      manyTableData: [],
      // 静态属性列表
      onlyTableData: [],
      // 图片上传url
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传设置上传的请求头部
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览开关
      prePictureVisible: false,
      // 图片预览url
      prePicUrl: ''
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // tab页签点击事件监听
    async tabClick (tab) {
      // console.log(tab.index === '1')
      const id = this.selectCateKeys[2]
      // alert(id)
      if (tab.index === '1') {
        const { data: res } = await this.$http.get('categories/' + id + '/attributes', {
          params: {
            sel: 'many'
          }
        })
        // console.log(res)
        if (res.meta.status !== 200) { return this.$message.error('获取动态参数失败！') }
        this.manyTableData = res.data
        console.log(this.manyTableData)
        // 将attr_vals字符串变为数组 attrVals
        this.manyTableData.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        // console.log(this.manyTableData)
      } else if (tab.index === '2') {
        const { data: res } = await this.$http.get('categories/' + id + '/attributes', {
          params: {
            sel: 'only'
          }
        })
        console.log(res)
        if (res.meta.status !== 200) { return this.$message.error('获取静态属性失败！') }
        this.onlyTableData = res.data
      }
    },
    // 获取所有的分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      // console.log(res)
      if (res.meta.status !== 200) { return this.$message.error('获取商品分类列表失败！') }
      // this.$message.success('获取商品分类列表成功！')
      this.cateList = res.data
    },
    // 监听级联选择框发生变化
    handleChange() {
      // 不能选择非三级的其他节点
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
      }
      this.addGoodsForm.goods_cat = this.selectCateKeys
      console.log(this.addGoodsForm.goods_cat)
    },
    // 切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
    beforeLeave(activeName, oldName) {
      if (activeName === '0') {
        return true
      }
      // console.log(activeName + '  ' + oldName)
      if (this.selectCateKeys.length !== 3) {
        this.$message.error('请填写商品分类')
        this.activeIndex = parseInt(oldName)
        return false
      }
      this.activeIndex = parseInt(activeName)
    },
    // 移除图片
    handleRemove(file) {
      // array.splice(start,delCount);//从start的位置开始向后删除delCount个元素
      // console.log(file)
      // array.findIndex() 寻找下标方法
      const i = this.addGoodsForm.pics.findIndex(x =>
        x.pic === file.response.data.tmp_path)
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm.pics)
    },
    // 图片上传预览
    handlePreview(file) {
      console.log(file)
      this.prePictureVisible = true
      this.prePicUrl = file.response.data.url
    },
    // 图片上传成功的勾子方法
    uploadSuccess(response) {
      // console.log(response)
      const pictureInfo = { pic: response.data.tmp_path }
      this.addGoodsForm.pics.push(pictureInfo)
      // console.log(this.addGoodsForm)
    },
    // 添加商品
    async addGood () {
      // console.log(this.addGoodsForm.goods_introduce)
      // 先进行预先验证
      this.$refs.addGoodsFormRef.validate(valid => {
        if (!valid) return this.$message.error('请填写表单的必要项')
      })
      // 提交表单
      if (typeof (this.addGoodsForm.goods_cat) !== 'string') {
        this.addGoodsForm.goods_cat = this.addGoodsForm.goods_cat.join(',')
        // console.log(this.addGoodsForm.goods_cat)
      }
      // 处理动态参数
      this.manyTableData.forEach(item => {
        const manyAttr = {
          attr_id: item.attr_id,
          // 数组转字符串
          attr_value: item.attr_vals.join(' ')
        }
        this.addGoodsForm.attrs.push(manyAttr)
      })
      // 处理静态属性
      this.onlyTableData.forEach(item => {
        const onlyAttr = {
          attr_id: item.attr_id,
          attr_value: item.attr_vals
        }
        this.addGoodsForm.attrs.push(onlyAttr)
      })
      console.log(this.addGoodsForm)
      // 向后台发起添加商品请求
      const { data: res } = await this.$http.post('goods', this.addGoodsForm)
      console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('添加商品失败')
      }
      this.$message.success('添加商品成功！')
      this.$router.push('/goods')
    }
  }
}
</script>

<style scoped>

</style>
